<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        $m = M('Users');
        
        
        /*
        插入数据
        $data = array(
            'username'=>'haiqin',
            'password'=>'111111',
            'create_time' => Date('Y-m-d H:i:s')
        );

        if($m->add($data)){
            echo 'success';
        }else{
            echo 'false';
        }
        */

        /*
        *修改数据
        
        $data = array(
            'uid'=>1,
            'username'=>'qinghai321'
        );

        if($m->save($data)){
            echo 'success';
        }else{
            echo 'false';
        }
        */

        //查数据
        //$user = $m->find(1);
        //$user = $m->where('uid = 1')->select();
        //$sql = 'select * from mini_users where uid = 1';
        //$user = $m->query($sql);
        //dump($user);

        //删除数据
        //$m->where('uid = 1')->delete();

        $this->display();
    }

    public function test(){
        $this->display();
    }

    /**
    * 注册接口
    */
    public function reg_post(){
        if(!$_REQUEST['username'] || !$_REQUEST['password']){
            _apiReturn(0,'用户名或密码为空！');
        }
        $m = M('Users');
        
        $user = $m->where('username = "'.$_REQUEST['username'].'"')->find();
        if($user){
            _apiReturn(0,"用户名已经使用！");
        }
        $data = array(
            'username'=>$_REQUEST['username'],
            'password'=>md5($_REQUEST['password']),
            'create_time' => Date('Y-m-d H:i:s')
        );
        if($m->add($data)){
            _apiReturn(1,"注册成功");
        }else{
            _apiReturn(0,'注册失败');
        }
    }

    public function login(){
        $this->display();
    }

    /**
    * 登录接口
    */
    public function login_post(){
        if(!$_REQUEST['username'] || !$_REQUEST['password']){
            _apiReturn(0,'用户名或密码为空！');
        }
        $m = M('Users');
        
        $map = array(
            'username' => $_REQUEST['username'],
            'password' => md5($_REQUEST['password'])
        );
        $user = $m->where($map)->find();

        if($user){
            unset($user['password']);
            unset($user['create_time']);
            $_SESSION['loginUser'] = $user;
            _apiReturn(1,"登录成功");
        }else{
            _apiReturn(0,"用户或密码错误");
        }
    }

    public function logout(){
        unset($_SESSION['loginUser']);
        echo "登出成功";
    }
}